from flask import (
    Blueprint, request, json, current_app
)
from urllib.parse import urlencode, quote, unquote
import urllib.request
from blemesh import db, util, error
from functools import wraps
import redis
from .error import error_handle

Myexception = error.Myexception
r = redis.StrictRedis(host='127.0.0.1', decode_responses=True)

user = db.User()
mesh = db.Mesh()

meshbp = Blueprint('mesh', __name__, url_prefix='/mesh')


def login_request(func):
    @wraps(func)
    def inner(*args, **kwargs):
        res = {
            'code': 0,
            'msg': ''
        }
        session_id = request.headers.get('sessionid')
        try:
            user_id = r.get(session_id)
            print("session_id = : ", session_id)
            print("从redis获取user_id: ", user_id)
        except:
            raise Exception("wrong in redis!")
        if user_id:
            r.expire(session_id, 7*24*60*60)
            if request.method == 'POST':
                req = json.loads(request.data)
                return func(user_id, req, res)
            if request.method == 'GET':
                return func(user_id, res)
        else:
            res['code']=100
            res['msg']='登录信息已过期，请重新登录！'
            return json.dumps(res)
    return inner


def requset_from_get(url, param):
    param = urlencode(param)
    url = url + '?' + param
    response = urllib.request.urlopen(url)
    response = response.read()
    response = json.loads(response.decode())
    print("从微信官网获得的反馈：", response)
    return response


def qrcode_from_post(url, param):
    textmod = json.dumps(param).encode(encoding='utf-8')
    print("textmod=", textmod)
    header_dict = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Trident/7.0; rv:11.0) like Gecko',
                   "Content-Type": "application/json"}
    req = urllib.request.Request(url=url, data=textmod, headers=header_dict)
    res = urllib.request.urlopen(req)
    res = res.read()
    return res



# *************登录**************
@meshbp.route('/login/', methods=['POST'])
@error_handle
def login():
        req = json.loads(request.data)
        res = {
            'code': 1,
            'msg': ''
        }
        url = 'https://api.weixin.qq.com/sns/jscode2session'
        param = {
            'appid': current_app.config.get('APPID'),
            'secret': current_app.config.get('APP_SECRET'),
            'js_code': req['code'],
            'grant_type': 'authorization_code'
        }
        response = requset_from_get(url, param)
        if('errcode' in response):
            raise Exception("无法从官网获取openid")
        openid = response['openid']
        result = user.get_user_info(openid)
        if not result:
            user.add_user(openid)
        session_id = util.ran_str(32)
        r.set(session_id, openid)
        r.expire(session_id, 3600)
        res['session_id'] = session_id
        res['msg'] = "login!"
        res['code'] = 0
        return json.dumps(res)


@meshbp.route('/set_user_info/', methods=['POST'])
@error_handle
@login_request
def set_user_info(user_id, req, res):
    print(req)
    nickname = req['nickName']
    avatarurl = req['avatarUrl']
    gender = req['gender']
    province = req['province']
    city = req['city']
    print("!!!!!!!!!!!!!!!!")
    country = req['country']
    print("!!!!!!!!!!!!!!!!")
    result=user.set_user_info(user_id,nickname,avatarurl,gender,province,city,country)
    if not result:
        res['code']=1
        res['msg']='添加用户信息失败'
    return json.dumps(res)


@meshbp.route('/get_user_info/', methods=['GET'])
@error_handle
@login_request
def get_user_info(user_id, res):
    print("user_id",user_id)
    print("res", res)
    res['userinfo']=user.get_user_info(user_id)
    result = user.get_user_info(user_id)
    print("get_user_info_result=",result)
    if result:
        res['userinfo']=result[0]
    else:
        res['code']=1
        res['msg']='没有这个人'
    return json.dumps(res)


# *************获取MESH列表************
@meshbp.route('/mesh_list/', methods=['GET'])
@error_handle
@login_request
def mesh_list(user_id, res):
    print("*************mesh_list***************")
    print("user_id = ", user_id)
    dbresult = mesh.meshs_by_user(user_id)
    print("mesh_list mesh.meshs_by_user ", dbresult)
    if dbresult:
        res['meshs'] = dbresult
    else:
        res['meshs'] = []
    res['code'] = 0
    res['msg'] = "mesh_list success中文!"
    return json.dumps(res)

# *************添加MESH***********
@meshbp.route('/mesh_add/', methods=['POST'])
@error_handle
@login_request
def mesh_add(user_id, req, res):
    net_key = req['netkey']
    app_key = util.ran_str(32)
    net_index = util.int_to_hexstr(1, 3)
    app_index = util.int_to_hexstr(1, 3)
    seq = "000000"
    address = "0001"
    node_address = "0101"
    iv_index = "00000001"
    ttl = 127
    name = req['meshname']
    virtual_address = "8000"
    group_address = "C000"
    dbresult = mesh.mesh_insert(net_key, app_key, net_index, app_index, seq, address, node_address, iv_index, ttl,
                                user_id, name, virtual_address, group_address)
    print("mesh_add:", dbresult)
    if (dbresult):
        res['mesh'] = {
            'id': dbresult['id'],
            'name': name,
            'net_key': net_key,
            'net_index': net_index,
            'app_key': app_key,
            'app_index': app_index,
            'seq': seq,
            'iv_index': iv_index,
            'address': address,
            'ttl': ttl
        }
        res['code'] = 0
        res['msg'] = "添加mesh成功！"

    else:
        res['msg'] = "添加mesh数据库出错！"
    return json.dumps(res)


@meshbp.route('/mesh_rename/', methods=['POST'])
@error_handle
@login_request
def mesh_rename(user_id, req, res):
    print("mesh_rename req = ", req)
    mesh_id = req['meshid']
    print("meshid = ", mesh_id)
    mesh_name = req['meshname']
    dbresult = mesh.update_name(mesh_id, mesh_name)
    if (dbresult):
        res['msg'] = "修改meshname成功！"
        res['code'] = 0
    else:
        res['msg'] = "修改meshname时数据库出错！"
    return json.dumps(res)


@meshbp.route('/mesh_update_seq/', methods=['POST'])
@error_handle
@login_request
def mesh_update_seq(user_id, req, res):
    print("mesh_update_seq req = ", req)
    meshid = req['meshid']
    seq = req['seq']
    dbresult = mesh.update_seq(meshid, seq)
    if (dbresult):
        res['code'] = 0
        res['msg'] = "修改seq成功!"
    else:
        res['msg'] = "修改seq时数据库出错!"
    return json.dumps(res)


@meshbp.route('/mesh_update_ivindex/', methods=['POST'])
@error_handle
@login_request
def mesh_update_ivindex(user_id, req, res):
    meshid = req['meshid']
    ivindex = req['ivindex']
    dbresult = mesh.update_ivindex(meshid, ivindex)
    if (dbresult):
        res['code'] = 0
        res['msg'] = "修改ivindex成功!"
    else:
        res['msg'] = "修改ivindex时数据库出错!"
    return json.dumps(res)


@meshbp.route('/delete_mesh/', methods=['POST'])
@error_handle
@login_request
def delete_mesh(user_id, req, res):
    mesh_id = req['meshid']
    dbresult = mesh.delete_mesh(mesh_id)
    if (dbresult):
        res['code'] = 0
        res['msg'] = "删除mesh成功!"
    else:
        res['msg'] = "删除mesh时数据库出错!"
    return json.dumps(res)


@meshbp.route('/all_control/', methods=['POST'])
@error_handle
@login_request
def all_control(user_id, req, res):
    mesh_id = req['meshid']
    warm = req['warm']
    cold = req['cold']
    red = req['red']
    green = req['green']
    blue = req['blue']
    dbresult = mesh.all_control(mesh_id, warm, cold, red, green, blue)
    res['code'] = 0
    res['msg'] = "全控成功!"
    return json.dumps(res)


@meshbp.route('/all_off/', methods=['POST'])
@error_handle
@login_request
def all_off(user_id, req, res):
    mesh_id = req['meshid']
    dbresult = mesh.all_off(mesh_id)
    res['code'] = 0
    res['msg'] = "全控成功!"
    return json.dumps(res)


@meshbp.route('/get_qrcodeurl/', methods=['GET'])
@error_handle
@login_request
def get_qrcodeurl(user_id, res):
    dbresult = user.if_login(user_id)
    if (dbresult):
        res['code'] = 0
        qrcode_url = dbresult['qrcode_url']
        print(type(qrcode_url))
        print("qrcode_url==", qrcode_url)
        qrcode_url = unquote(qrcode_url)
        print("qrcode_url===", qrcode_url)

        res['qrcode_url'] = qrcode_url
    else:
        res['msg'] = "获取二维码出错!"
    return json.dumps(res)
